<template>
	<view>
		<view class="search-area">
			<uni-search-bar @input="input" :radius="20" cancelButton="none"></uni-search-bar>
		</view>
		<view class="sugg-list" v-if="searchList.length">
			<view class="list-item" v-for="(item, i) in searchList" :key="i" @click="jumpDetail(item)">
				<view class="name">{{ item.goods_name }}</view>
				<uni-icons type="arrowright" size="16"></uni-icons>
			</view>
		</view>
		<view class="history-box" v-else>
			<view class="history-opration">
				<text>搜索历史</text>
				<uni-icons type="trash" @click="deleteAll"></uni-icons>
			</view>
			<view class="history-list">
				<uni-tag @click="jumpHistory(item)" class="history-item" v-for="(item, i) in histories" :key="i" :text="item">
				</uni-tag>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				timer: null,
				kw: '', // 搜索关键词
				searchList: [],
				historyList: []
			};
		},
		computed: {
			histories() {
				// 保存历史记录(新值排列顺序要在最前、去重)
				return [...this.historyList].reverse()
			}
		},
		onLoad(){
			this.historyList = JSON.parse(uni.getStorageSync('kw') || '[]')
		},
		methods: {
			input(e) {
				// 每次触发延时器时，先清除上一个
				clearTimeout(this.timer)
				// 给搜索框添加防抖处理
				// 500毫秒内,如果没有触发事件，就为搜索框赋值
				this.timer = setTimeout(()=> {
					this.kw = e
					this.getSearchList()
				}, 500)
			},
			async getSearchList() {
				if(this.kw === '') {
					this.searchList = []
					return
				}
				const { data } = await uni.$http.get('/api/public/v1/goods/qsearch', { query: this.kw })
				if(data.meta.status !== 200) return uni.$showMsg()
				this.searchList = data.message
				this.saveSearchHistory()
			},
			jumpDetail(item) {
				uni.navigateTo({
					url: '/subpkg/goods_detail/goods_detail?goods_id=' + item.goods_id
				})
			},
			saveSearchHistory() {
				// 保存历史记录(新值排列顺序要在最前、去重)
				const set = new Set(this.historyList)
				set.delete(this.kw)
				set.add(this.kw)
				this.historyList = Array.from(set)
				uni.setStorageSync('kw', JSON.stringify(this.historyList))
			},
			deleteAll() {
				this.historyList = []
				uni.removeStorageSync('kw')
			},
			jumpHistory(item) {
				uni.navigateTo({
					url: '/subpkg/goods_list/goods_list?query=' + item
				})
			}
		}
	}
</script>

<style lang="scss">
.search-area {
	position: sticky; // 吸顶效果
	top: 0;
	z-index: 999; // 防止轮播图覆盖之上
}
.sugg-list {
	.list-item {
		display: flex;
		justify-content: space-between;
		height: 50px;
		line-height: 50px;
		padding: 0 10px;
		border-bottom: 1px solid #efefef;
		.name {
			overflow: hidden;
			white-space: nowrap;
			text-overflow: ellipsis;
			font-size: 12px;
		}
	}
	.list-item:last-child {
		border-bottom: none;
	}
}
.history-box {
	.history-opration {
		display: flex;
		justify-content: space-between;
		padding: 10px;
		border-bottom: 1px solid #efefef;
	}
	.history-list {
		margin-top: 10px;
		
		.history-item {
			margin: 5px;
		}
	}
}
</style>
